package com.qsw.refreshrecyclerview.RefreshRecyclerView.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

import java.util.Collections;

/**
 * 拖拽排序处理
 */
public class OnItemTouchHelperCallBack extends ItemTouchHelper.Callback {

    @Override
    public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
        // 定义拖动和滑动的方向
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        int swipeFlags = 0; // 这里设为0，表示不可滑动删除
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    // 拖动时回调此方法
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
        // 获取拖动前后的位置
        int from = viewHolder.getAdapterPosition();
        int to = target.getAdapterPosition();

        // 执行数据交换操作
        RecyclerView.Adapter adapter = recyclerView.getAdapter();
        if (adapter instanceof HeaderFooterRecyclerAdapter) {
            HeaderFooterRecyclerAdapter headerFooterRecyclerAdapter = (HeaderFooterRecyclerAdapter) adapter;
            adapter = headerFooterRecyclerAdapter.getAdapter();
            if (adapter != null && adapter instanceof RefreshRecyclerViewAdapter) {
                int innerFrom = from - headerFooterRecyclerAdapter.getHeaderCount();
                int innerTo = to - headerFooterRecyclerAdapter.getHeaderCount();
                RefreshRecyclerViewAdapter refreshRecyclerViewAdapter = (RefreshRecyclerViewAdapter) adapter;

                if (refreshRecyclerViewAdapter.getItemCount() > 0
                        && innerFrom >= 0
                        && innerFrom < refreshRecyclerViewAdapter.getItemCount()
                        && innerTo >= 0
                        && innerTo < refreshRecyclerViewAdapter.getItemCount()
                ) {
                    Collections.swap(refreshRecyclerViewAdapter.getData(), innerFrom, innerTo);
                    refreshRecyclerViewAdapter.notifyItemMoved(from, to);
                    return true;
                }
            }
        }
        return false;
    }

    // 滑动时回调此方法
    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        // 不处理滑动操作
    }
}